﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace XmlServer.Admin
{
    public partial class MainForm : Form
    {
        System.Timers.Timer timer;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
           
            timer = new System.Timers.Timer();
            timer.Elapsed += timer_Elapsed;

            cboGraph.SelectedIndex = 0;

            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        }

        private void chkMonitor_CheckedChanged(object sender, EventArgs e)
        {
            
            if (chkMonitor.Checked == false)
            {
                timer.Enabled = false;
                this.txtIPAddress.Enabled = true;
                this.txtPort.Enabled = true;
                this.txtRefresh.Enabled = true;
            }
            else
            {
                if (String.IsNullOrEmpty(this.txtIPAddress.Text))
                {
                    MessageBox.Show("Please enter in the XmlServer IPAddress");
                    this.txtIPAddress.Focus();
                    return;
                }

                if (String.IsNullOrEmpty(this.txtPort.Text))
                {
                    MessageBox.Show("Please enter in the XmlServer Port");
                    this.txtPort.Focus();
                    return;
                }

                int port = 0;
                if (!Int32.TryParse(txtPort.Text, out port) && port > 0)
                {
                    MessageBox.Show("Please enter in the XmlServer Port.  The value must be greater than zero.");
                    this.txtPort.Focus();
                    return;
                }

                if (String.IsNullOrEmpty(this.txtRefresh.Text))
                {
                    MessageBox.Show("Please enter in the XmlServer Status Refresh Rate");
                    this.txtRefresh.Focus();
                    return;
                }

                int refresh = 0;
                if (!Int32.TryParse(txtRefresh.Text, out refresh) && refresh >= 1)
                {
                    MessageBox.Show("Please enter in the XmlServer Status Refresh Rate.  The value must be greater than or equal to 1.");
                    this.txtRefresh.Focus();
                    return;
                }

                this.txtIPAddress.Enabled = false;
                this.txtPort.Enabled = false;
                this.txtRefresh.Enabled = false;

                MakeStatusRequest();
                timer.Interval = refresh * 1000;
                timer.Enabled = true;

            }
             
        }

        public void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            MakeStatusRequest();
        }

        public void MakeStatusRequest()
        {
            try
            {
                // get the request string
                string request = XmlServer.Helper.Utilities.CreateRequest("Status", "1.0", null);

                var response = XmlServer.Helper.Utilities.MakeRequest(request, this.txtIPAddress.Text, Convert.ToInt32(this.txtPort.Text));
                var success = XmlServer.Helper.Utilities.IsResponseSuccess(response);
                if (success)
                {

                    var facts = XmlServer.Helper.Utilities.GetFacts(response, true);
                                                            
                    var waiting = XmlServer.Helper.Utilities.GetFact(facts, "ClientPoolCount");
                    var processed = XmlServer.Helper.Utilities.GetFact(facts, "ClientsProcessed");
                    var avgTime = XmlServer.Helper.Utilities.GetFact(facts, "ClientAverageTime");
                    var totalTime = XmlServer.Helper.Utilities.GetFact(facts, "ClientsTotalTime");
                    var cleanup = XmlServer.Helper.Utilities.GetFact(facts, "EstimatedCleanupTime");
                                                             
                    if (this.InvokeRequired)
                    {                        
                        this.Invoke(new UpdateInterfaceDelegate(UpdateInterface),
                            new object[] { DateTime.Now.ToLongTimeString(), waiting, processed, avgTime, totalTime, cleanup });
                    }
                    else
                    {
                        UpdateInterface(DateTime.Now.ToLongTimeString(), waiting, processed, avgTime, totalTime, cleanup);
                    }
                }
                else
                {
                    timer.Enabled = false;
                    MessageBox.Show("Failed to get the status from the server.  Please try a different XmlServer");
                    chkMonitor.Checked = false;                    
                }

            }
            catch (Exception err)
            {
                // do nothing
                timer.Enabled = false;
                MessageBox.Show("Failed to get the status from the server.  Please try a different XmlServer.\n\n" + err.Message);
                chkMonitor.Checked = false;
            }
            

        }

        public delegate void UpdateInterfaceDelegate(string lastUpdated, string waiting, string processed, string avgTime, string totalTime, string cleanup);
        public void UpdateInterface(string lastUpdated, string waiting, string processed, string avgTime, string totalTime, string cleanup)
        {
            lblLastUpdated.Text = lastUpdated;
            lblClientsWaiting.Text = waiting;
            lblProcessed.Text = processed;
            lblAverage.Text = avgTime;
            lblTotal.Text = totalTime;
            lblCleanup.Text = cleanup;

            decimal perfMonitorValue = 0;
            bool graphValue = true;


            var graphType = this.cboGraph.SelectedItem.ToString();

            if (graphType == "Clients Waiting")
            {
                graphValue = decimal.TryParse(waiting, out perfMonitorValue);
            }
            else if (graphType == "Clients Processed")
            {
                graphValue = decimal.TryParse(processed, out perfMonitorValue);
            }
            else if (graphType == "Client Total Time")
            {
                graphValue = decimal.TryParse(totalTime, out perfMonitorValue);
            }
            else if (graphType == "Client Average Time")
            {
                graphValue = decimal.TryParse(avgTime, out perfMonitorValue);
            }
            else if (graphType == "Estimated Cleanup Time")
            {
                graphValue = decimal.TryParse(cleanup, out perfMonitorValue);
            }

            if (graphValue)
            {
                this.perfChart1.AddValue(perfMonitorValue);                
            }

            

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer.Enabled = false;
        }

        private void cboGraph_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.perfChart1.Clear();
        }



    }
}
